// /pages/exam/exam-category/exam-category.ts
// 定义类型
interface CategoryData {
    id: number;
    name: string;
    parentId: number | null;
    paperId: number | null;
    level: number;
    orderNum: number;
}

Page({
    data: {
        categoryId: 0,
        categoryName: "",
        treeData: [] as any[]
    },

    onLoad(options: any) {
        const categoryId = parseInt(options.id);
        this.setData({categoryId});
        this.loadCategoryData(categoryId);
    },

    async loadCategoryData(categoryId: number) {
        wx.showLoading({
            title: '加载中...',
            mask: true
        });

        try {
            const categoryData = await this.getCategoryData(categoryId);
            const treeData = categoryData.children || [];
            
            this.setData({
                categoryName: categoryData.name,
                treeData: treeData
            });
        } catch (error) {
            console.error('加载分类数据失败:', error);
            wx.showToast({title: '加载失败', icon: 'error'});
        } finally {
            wx.hideLoading();
        }
    },

    // 处理节点点击
    handleNodeTap(e: any) {
        const paperId = e.currentTarget.dataset.paperId;
        if (paperId) {
            wx.navigateTo({
                url: `/pages/exam/exam-record/exam-record?paperId=${paperId}`
            });
        }
    },

    // 从网络获取分类数据
    async getCategoryData(categoryId: number): Promise<any> {
        const app = getApp<IAppOption>();
        //debugger
        return new Promise<any>((resolve, reject) => {
            wx.request({
                url: app.buildApiUrl(`/api/exam-paper-categories/tree/${categoryId}`),
                method: 'GET',
                header: {'Authorization': wx.getStorageSync('token')},
                success: (res) => {
                    if (res.statusCode === 200) {
                        resolve(res.data);
                    } else {
                        reject(new Error(`请求失败，状态码: ${res.statusCode}`));
                    }
                },
                fail: (err) => {
                    reject(err);
                }
            });
        });
    }
});